package com.lzs.OkHttpDownload;


import android.Manifest;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private EditText editText;//输入下载地址
    private Button startButton;
    private Button pauseButton;
    private Button cancleButton;//开始、暂停、取消下载按钮
    private ProgressBar downloadProgressBar;//进度条
    private TextView downloadProgressText;//进度百分比展示
    // 下载任务
    private downloadTask downloadtask1;
    // 标记当前任务是否在下载，解决多次连续点击‘开始下载’出错的问题
    private boolean isDownloading = false;
    // 使用正则表达式来判断用户的输入是否是一个网址
    // 参考：https://blog.csdn.net/qq_25384945/article/details/81219075
    private Pattern httpPattern = Pattern.compile("^(https?|http)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");


    @Override
    protected void onCreate(Bundle saveInstanceState) {
//        Android6.0之后需要动态申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_main);//绑定UI组件
        editText = (EditText) findViewById(R.id.downloadurl);
        startButton = (Button) findViewById(R.id.start_download);
        pauseButton = (Button) findViewById(R.id.pause_download);
        cancleButton = (Button) findViewById(R.id.cancel_download);
        downloadProgressBar = (ProgressBar) findViewById(R.id.download_progress);
        downloadProgressText = (TextView) findViewById(R.id.download_progress_text);
        startButton.setOnClickListener(this);
        pauseButton.setOnClickListener(this);
        cancleButton.setOnClickListener(this);
    }

    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.start_download:
                // 如果当前任务正在下载中，不会重新开始下载任务，避免多次点击‘开始下载’卡顿
                if (isDownloading) {
                    Toast.makeText(this, "下载正在进行中", Toast.LENGTH_SHORT).show();
                    break;
                }
                // 正则表达式对用户输入进行判断是否是一个URL
                if (!httpPattern.matcher(editText.getText().toString()).matches()) {
                    Toast.makeText(this, "输入地址有误", Toast.LENGTH_SHORT).show();
                    break;
                }
                // 创建AsyncTask子类的实例对象(即 任务实例)，必须在UI线程中创建
                downloadtask1 = new downloadTask(new downloadListener() {
                    @Override
                    public void onProgress(int progress) {
                        downloadProgressBar.setProgress(progress);
                        downloadProgressText.setText(progress + "%");
                    }

                    @Override
                    public void onSuccess() {
                        Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                        isDownloading = false;
                    }

                    @Override
                    public void onFailed() {
                        Toast.makeText(MainActivity.this, "网络(or文件权限)异常，下载失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onPause() {
                        isDownloading = false;
                        downloadtask1.pauseDownload();
                        Toast.makeText(MainActivity.this, "下载暂停", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancle() {
                        isDownloading = false;
                        downloadtask1.onCancelled();
                        Toast.makeText(MainActivity.this, "下载取消", Toast.LENGTH_SHORT).show();
                    }
                });
                // 如果输入为空，则提示用户进行输入，避免将一个空URL传递给doInBackground()造成应用闪退
                if ("".equals(editText.getText().toString())) {
                    Toast.makeText(this, "请输入下载地址", Toast.LENGTH_SHORT).show();
                    break;
                }
                // 手动调用execute()从而执行异步线程任务，同一个AsyncTask对象只能执行一次，第二次会抛出异常
                // 执行任务中，系统会自动调用AsyncTask的一系列方法：onPreExecute() 、doInBackground()、onProgressUpdate() 、onPostExecute()
                // 开始下载任务，将isDownloading标记为true，同时弹出Toast通知提示用户
                downloadtask1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, editText.getText().toString());
                isDownloading = true;
                Toast.makeText(this, "开始下载", Toast.LENGTH_SHORT).show();
                break;
            case R.id.pause_download:
                // 如果输入为空，则提示用户进行输入，避免将一个空URL传递给doInBackground()造成应用闪退
                if ("".equals(editText.getText().toString())) {
                    Toast.makeText(this, "当前没有下载任务", Toast.LENGTH_SHORT).show();
                    break;
                }
                downloadtask1.pauseDownload();
                if (!isDownloading) {
                    Toast.makeText(this, "下载已暂停", Toast.LENGTH_SHORT).show();
                }
                isDownloading = false;
                break;
            case R.id.cancel_download:
                // 取消一个正在执行的任务，onCancleed()方法将会被调用
                // 如果输入为空，则提示用户进行输入，避免将一个空URL传递给doInBackground()造成应用闪退
                if ("".equals(editText.getText().toString())) {
                    Toast.makeText(this, "当前没有下载任务", Toast.LENGTH_SHORT).show();
                    break;
                }
                downloadtask1.onCancelled();
                if (!isDownloading) {
                    Toast.makeText(this, "下载已取消", Toast.LENGTH_SHORT).show();
                }
                isDownloading = false;
                break;
        }
    }
}